package com.example.word.ui.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.dict.R;
import com.example.word.bean.Browse;
import com.example.word.bean.Collect;
import com.example.word.bean.Dict;
import com.example.word.bean.StudyPlan;
import com.example.word.bean.Word;
import com.example.word.ui.activity.BrowseActivity;
import com.example.word.ui.activity.LoginActivity;
import com.example.word.ui.activity.SearchWordActivity;
import com.example.word.ui.activity.StudyPlanActivity;
import com.example.word.ui.activity.UnitActivity;
import com.example.word.ui.activity.WordReviewActivity;
import com.example.word.ui.activity.WordStudyActivity;
import com.example.word.util.AlwaysMarqueeTextView;
import com.example.word.util.CommonUtils;
import com.example.word.util.HttpUtils;
import com.example.word.util.MessageUtils;
import com.example.word.util.SPUtils;
import com.example.word.util.StringUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 首页Fragment
 */
public class StudyFragment extends Fragment {
    private Activity myActivity;
    private Boolean mIsAdmin;
    private boolean iscbAll = false;
    private List<Dict> mDict = new ArrayList<>();
    private String account;
    private Button startStudy;
    private TextView editDict, reviewCount, todayCount, totalCount, currentUserDict, dictStudyCount,isDone;
    private AlwaysMarqueeTextView systemMsg;
    private StudyPlan currentStudyPlan;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        myActivity = (Activity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_study, container, false);
        //获取控件
        startStudy = view.findViewById(R.id.startStudy);
        // 设置按钮主题
        if (!com.example.word.ui.activity.MainActivity.colorChange) {
            startStudy.setBackground(getResources().getDrawable(R.drawable.btn_border_fill));
        } else {
            startStudy.setBackground(getResources().getDrawable(R.drawable.btn_border_fill_my_color));
        }
        editDict = view.findViewById(R.id.editDict);
        dictStudyCount = view.findViewById(R.id.dictStudyCount);
        reviewCount = view.findViewById(R.id.reviewCount);
        todayCount = view.findViewById(R.id.todayCount);
        totalCount = view.findViewById(R.id.totalCount);
        currentUserDict = view.findViewById(R.id.currentUserDict);
        isDone = view.findViewById(R.id.isDone);
        systemMsg = view.findViewById(R.id.systemMsg);

//        reviewCount.setPaintFlags(reviewCount.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
//        todayCount.setPaintFlags(todayCount.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
//        totalCount.setPaintFlags(totalCount.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
        currentUserDict.setPaintFlags(currentUserDict.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
        initView();
        return view;
    }

    private void initView() {
        mIsAdmin = (Boolean) SPUtils.get(myActivity, SPUtils.IS_ADMIN, false);
        account = (String) SPUtils.get(myActivity, SPUtils.ACCOUNT, "");
        LinearLayoutManager layoutManager = new LinearLayoutManager(myActivity);
        //=1.2、设置为垂直排列，用setOrientation方法设置(默认为垂直布局)
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        //开始学习
        startStudy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 如果当前词汇的单词未下载，先进行下载
                String currentUserDictTitle = currentUserDict.getText().toString();
                Map<String, String> requestParam = new HashMap<>();
                requestParam.put("dict", currentUserDictTitle);
                // 调用 API 客户端的方法
                HttpUtils.sendGetRequest("/getDictList", requestParam, myActivity, Dict.class, response -> {
                    if (response.getDataList().isEmpty()) {
                        MessageUtils.show("当前词汇不存在，请切换词汇", myActivity);
                        return;
                    }
                    startStudyActivity(response.getDataList().get(0));
                });
            }
        });

        //切换词汇
        editDict.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 根据单元（页数），和总数进行查询
                Intent intent = new Intent(myActivity, StudyPlanActivity.class);
                startActivityForResult(intent, 100);
            }
        });

        // 点击今日新词
        todayCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(myActivity, BrowseActivity.class);
                startActivity(intent);
            }
        });

        // 点击总计学习
        totalCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(myActivity, BrowseActivity.class);
                startActivity(intent);
            }
        });

        // 点击待复习
        reviewCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(myActivity, WordReviewActivity.class);
                startActivity(intent);
            }
        });
    }

    private void startStudyActivity(Dict dict) {
        // 根据单元（页数），和总数进行查询
        Intent intent = new Intent(myActivity, WordStudyActivity.class);

        // 查询出当前词汇用户已学习的单词
        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("dict", dict.getDict());
        // 调用 API 客户端的方法
        HttpUtils.sendGetRequest("/getCanStudyWordList", requestParam, myActivity, Word.class, collectResponse -> {
            List<Word> wordList = collectResponse.getDataList();
            List<String> wordArray = new ArrayList<>();
            for (Word word : wordList) {
                wordArray.add(word.getWord());
            }
            intent.putExtra("wordArray", wordArray.toArray(new String[0]));
            intent.putExtra("dict", dict.getDict());

            startActivityForResult(intent, 100);
        });
    }

    /**
     * 加载数据
     */
    public void loadData(Activity... activities) {
        if (StringUtils.isEmpty(account)) {
            return;
        }

        // 调用 API 客户端的方法
        HttpUtils.sendGetRequest("/getUserStudyPlan", new HashMap<>(), activities.length > 0 ? activities[0] : myActivity, StudyPlan.class, response -> {
            // 加载当前用户学习情况 dayTask,todayCount,totalCount, currentUserDict;
            StudyPlan studyPlan = response.getData();
            currentStudyPlan = studyPlan;

            reviewCount.setText(String.valueOf(studyPlan.getReviewCount()));
            todayCount.setText(String.valueOf(studyPlan.getTodayCount()));
            totalCount.setText(String.valueOf(studyPlan.getTotalCount()));
            currentUserDict.setText(studyPlan.getDict());
            dictStudyCount.setText("(" + studyPlan.getDictStudyCount() + " / " + studyPlan.getDictWordCount() + ")");
            isDone.setText("未完成今日学习任务~");
            startStudy.setText("开始学习");
            if (studyPlan.getTodayCount() >= studyPlan.getDayTask()) {
                isDone.setText("已完成今日学习任务~");
                startStudy.setText("继续学习");
            }

            systemMsg.setText(String.format("系统消息: 您今日学习目标为%s个单词，今日已学习%s个单词，累计学习了%s个单词，继续加油噢！", studyPlan.getDayTask(), studyPlan.getTodayCount(), studyPlan.getTotalCount()));

        });
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            loadData();
        }
    }

    public void setColor() {
        // 设置按钮主题
        if (!com.example.word.ui.activity.MainActivity.colorChange) {
            startStudy.setBackground(getResources().getDrawable(R.drawable.btn_border_fill));
        } else {
            startStudy.setBackground(getResources().getDrawable(R.drawable.btn_border_fill_my_color));
        }
    }

}
